<?php

function fetch($url) {
	$curl = curl_init();
	
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	$result = curl_exec($curl);
	curl_close($curl);
	
	return $result;
}


function grab() {		
	$temp = array();
	$today = date('Y/m/d');
	$nextUrl = "http://www.nba.com/.element/ssi/auto/1.0/aps/video/$today/recent_whatsnew_include1.html";

	while ($nextUrl) {
		$content = fetch($nextUrl);
		//echo $nextUrl . "\n";
		
		//Find the next URL.
		$pattern = '/(\d+\/\d+\/\d+\/recent_whatsnew_include\d+.html)\'\);">\n/i';
		if (preg_match($pattern, $content, $matches)) {
			$nextUrl = "http://www.nba.com/.element/ssi/auto/1.0/aps/video/$matches[1]";
		} else {
			$nextUrl = false;
		}

		$pattern = '/<img src="([^"]+)"><span class="nbaSpanOverlay"><\/span><\/div><\/a><a class="nbaVideoGridContentHeader" href="\/video\/games\/([^\/]+\/(\d+\/\d+\/\d+)\/[^\.]+\.nba)\/whatsnew\/index.html">([^<]+vs.[^<:]+)<\/a><div class="nbaVideoGridTextBlock">([^<]+)<\/div>/i';
		if ($count = preg_match_all($pattern, $content, $matches)) {
			for ($i = 0; $i < $count; $i++) {
				$temp[] = array(
					$matches[4][$i], //Game Name
					$matches[3][$i], //Date
					$matches[5][$i], //Description
					$matches[1][$i], //Thumbnail
					"http://nba.cdn.turner.com/nba/big/games/" . $matches[2][$i] . "_nba_576x324.flv"
				);
			}
		}
	}

	$result = array();
	foreach ($temp as $val) {
		list($team1, $team2) = split('[ ]+vs.[ ]+', $val[0]);
		list($year, $month, $day) = split('/', $val[1]);
		$index = "$team1 $team2 $month/$day/$year";
		
		$result[$index] = array(
			'name' => $val[0], //Team vs Team
			'date' => $val[1], //Date
			'description' => $val[2], //Description
			'thumbnail' => $val[3], //Thumbnail
			'video' => $val[4] //Video
		);
	}

	return $result;
}

function searchNews($away, $home, $date) {
	$ts = strtotime($date);
	$days = ceil((time() - intval($ts)) / (3600 * 24));
	
	$url = "http://query.yahooapis.com/v1/public/yql?format=json&callback=&q=" . urlencode("select title, abstract, clickurl from search.news where query=\"$away, $home\" and age=\"{$days}d\"");
	

	$data = json_decode(fetch($url), true);

	if (isset($data['query']['results']['result'])) {
		return $data['query']['results']['result'];
	} else {
		return null;
	}
}

function searchNbaVideo($away, $home, $date) {
	$cacheFile = '/tmp/grabcache';
	$database = null;
	$stat = @stat($cacheFile);
	if (!$stat || (time() - $stat['mtime']) > 3600) {
		$fd = fopen($cacheFile, 'w');
		if ($fd) {
			$database = grab();
			fwrite($fd, json_encode($database));
			fclose($fd);
		} else {
			die('Unable to open file');
		}
	} else {
		$fd = fopen($cacheFile, 'r');
		$database = json_decode(fread($fd, $stat['size']), true);
		//echo "Count:" . count($database);
		fclose($fd);
	}

	//$database = grab();
	//var_dump($database);
	
	list($m, $d, $y) = split('/', $date);
	$pattern = "/" . $away . "[ ]+" . $home . "[ ]+$m\/$d\/$y/i";
	
	$result = null;
	foreach ($database as $key => $value) {
		if (preg_match($pattern, $key)) {
			$result = $database[$key];
			break;
		}
	}

	if ($result) {
		$news = searchNews($away, $home, $date);
		if ($news) {
			$result['news'] = $news;
		}
	}

	return $result;
}


//var_dump(searchNbaVideo('Suns', 'Lakers', '02/26/2009'));


$away = $_REQUEST['away'];
$home = $_REQUEST['home'];
$date = $_REQUEST['date'];

echo json_encode(searchNbaVideo($away, $home, $date));
?>
